/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.revivius.jbtorrent.util;

import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Map;
import org.ardverk.coding.BencodingOutputStream;

/**
 *
 * @author Revivius
 */
public class HashUtil {

    private static final String HASH_ALGO = "SHA-1";

    public static byte[] hash(byte[] data) throws Exception {
        MessageDigest md = MessageDigest.getInstance(HASH_ALGO);
        byte[] hash = md.digest(data);

        return hash;
    }

    public static byte[] hash(Map<String, Object> info) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BencodingOutputStream bos = new BencodingOutputStream(baos);
        bos.writeObject(info);
        
        bos.close();
        baos.close();
        
        return hash(baos.toByteArray());
    }
    
    public static String toHex(byte[] hash) {
        return new BigInteger(1, hash).toString(16);
    }

}
